package com.tepth.vehiclemaintenance.mvp.work.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.base.BaseBackFragment;
import com.tepth.vehiclemaintenance.bean.MaintainListWork;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.event.SearchResultEvent;
import com.tepth.vehiclemaintenance.tools.SPUtils;
import com.tepth.vehiclemaintenance.tools.Utils;
import com.tepth.vehiclemaintenance.ui.view.dialog.DialogDelegate;
import com.tepth.vehiclemaintenance.ui.view.dialog.SweetAlertDialogDelegate;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by zhangyu on 2017/5/16.
 */

public class SearchFragment extends BaseBackFragment implements SearchContract.View {
    private static final String PARAMETER = "Operator";

    public static SearchFragment newInstance(MaintainListWork.ListContentsBean.ListRemarkBean.OperationBean operationBean) {
        SearchFragment fragment = new SearchFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAMETER, operationBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.et_search)
    EditText mEditTextSearch;
    @BindView(R.id.id_tag_flow_layout)
    TagFlowLayout mTagFlowLayout;
    @BindView(R.id.tv_action)
    TextView mTextViewAction;
    @BindView(R.id.list_view)
    ListView mListView;
    @BindView(R.id.layout_empty)
    LinearLayout mLayoutEmpty;
    //推荐的部件Accessory个数
    private int mRecommendAcSize;
    //搜索的部件Accessory个数
    private int mSearchAcSize;
    private DialogDelegate mDialogDelegate;
    private SearchContract.Presenter mPresenter;
    private MaintainListWork.ListContentsBean.ListRemarkBean.OperationBean mOperationBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mOperationBean = (MaintainListWork.ListContentsBean.ListRemarkBean.OperationBean)
                    bundle.getSerializable(PARAMETER);
        }
    }

    @Override
    protected void setPresenter() {
        mPresenter = new SearchPresenter();
        SearchContract.Model model = new SearchModel();
        mPresenter.setVM(this, model);
    }

    @Override
    protected void unbindPresenter() {
        mPresenter.onDestroy();
    }

    @Override
    protected void initView(View view) {
        mToolbar.setTitle("部件搜索");
        initToolbarNav(mToolbar);

        mDialogDelegate = new SweetAlertDialogDelegate(_mActivity);
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_search:
                        onSearch(mEditTextSearch.getText().toString().trim());
                        break;
                }
                return true;
            }
        });
        mEditTextSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        mEditTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearch(mEditTextSearch.getText().toString().trim());
                    Utils.hideInputMethod(v);
                    return true;
                }
                return false;
            }
        });
        mTextViewAction.setText(getString(R.string.search_result) +
                "(" + mOperationBean.getName() + ")");
        mPresenter.getCommonComponents();
        mDialogDelegate.showProgressDialog(true, getString(R.string._loading));
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_part_search, container, false);
    }

    @Override
    public void onNetworkError(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(_mActivity, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getName() {
        return mEditTextSearch.getText().toString().trim();
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public void showSearchResult(int accessorySize, int componentSize, ArrayList<MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean> list) {
        mDialogDelegate.clearDialog();
        if (list == null || list.isEmpty()) {
            mLayoutEmpty.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);
        } else {
            mSearchAcSize = accessorySize;
            mLayoutEmpty.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
            final ArrayAdapter<MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean> adapter
                    = new ArrayAdapter<>(_mActivity, R.layout.item_text, list);
            mListView.setAdapter(adapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean part =
                            adapter.getItem(position);
                    setIntentData(position, mSearchAcSize, part);
                }
            });
        }
    }

    @Override
    public void showCommonComponents(int accessorySize, int componentSize, ArrayList<MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean> list) {
        mDialogDelegate.clearDialog();
        if (!list.isEmpty()) {
            mRecommendAcSize = accessorySize;
            setTagLayout(list);
        }
    }

    public void onSearch(String key) {

        if (!key.isEmpty()) {
            mPresenter.search();
            mDialogDelegate.showProgressDialog(true, "正在搜索,请稍候...");
        }

    }

    private void setTagLayout(ArrayList<MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean> list) {
        final LayoutInflater inflater = LayoutInflater.from(_mActivity);
        final TagAdapter<MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean> tagAdapter
                = new TagAdapter<MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean>(list) {
            @Override
            public View getView(FlowLayout parent, int position,
                                MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean part) {
                TextView tv = (TextView) inflater.inflate(R.layout.view_tv,
                        parent, false);
                tv.setText(part.getName());
                return tv;
            }
        };
        mTagFlowLayout.setMaxSelectCount(1);
        mTagFlowLayout.setAdapter(tagAdapter);
        mTagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                //TODO 需要知道选中的是哪个list里面的数据
                MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean part = tagAdapter.getItem(position);
                setIntentData(position, mRecommendAcSize, part);
                return false;
            }
        });
    }

    private void setIntentData(int position, int referenceValue,
                               MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean part) {
        int type;
        if (position <= referenceValue - 1) {
            type = 0;
        } else {
            type = 1;
        }
        EventBus.getDefault().post(new SearchResultEvent(mOperationBean, part, type));
        pop();
    }
}
